import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import {asyncRouters,anyRouters,constantRoutes} from '@/router'
import router from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    //用户名称
    name: '',
    //头像
    avatar: '',
    //按钮
    buttons:[],
    //角色
    roles:[],
    //路由
    routes:[],
    //异步路由计算结果
    resultAsyncRoutes:[],
    //最终路由
    resultAllRoutes:[],
  }
}

const resultAsyncRoutes = (asyncRouters,routes)=>{
   return asyncRouters.filter(item=>{
     if(routes.indexOf(item.name)!==-1){
       if(item.children && item.children.length){
         item.children = resultAsyncRoutes(item.children,routes)
       }
       return true
     }
   })
}

const resultAllRoutes = (asyncRouters,anyRouters,constantRoutes)=>{
  //合并
  return asyncRouters.concat(anyRouters,constantRoutes)
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_BUTTONS:(state,buttons)=>{
    state.buttons = buttons
  },
  SET_ROLES:(state,roles)=>{
    state.roles = roles
  },
  SET_ROUTES:(state,routes)=>{
    state.routes = routes
    state.resultAsyncRoutes = resultAsyncRoutes(asyncRouters,routes)
    state.resultAllRoutes = resultAllRoutes(state.resultAsyncRoutes,anyRouters,constantRoutes)
    router.addRoutes(state.resultAllRoutes)
  },
}

const actions = {
  // 处理登录业务
  async login({ commit }, userInfo) {
    //解构出用户名和密码
    const { username, password } = userInfo
    let result = await login({ username: username.trim(), password: password })
    //mock数据code是20000
    if (result.code === 20000){
      commit('SET_TOKEN', result.data.token)
      setToken(result.data.token)
      return 'ok'
    }else{
      return Promise.reject(new Error(result.message))
    }
    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     const { data } = response
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { name, avatar,buttons,roles,routes } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_BUTTONS', buttons)
        commit('SET_ROLES', roles)
        commit('SET_ROUTES', routes)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

